package com.share.ai.langchain4j.config;

import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.mcp.McpToolProvider;
import dev.langchain4j.mcp.client.DefaultMcpClient;
import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.transport.McpTransport;
import dev.langchain4j.mcp.client.transport.stdio.StdioMcpTransport;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;


@Configuration
public class McpConfig {
    private static final String jarPath="E:\\share\\project\\share-ai\\mcp-server-stdio\\target\\mcp-server-stdio.jar";

    //stdio方式实现
    @Bean
    public StdioMcpTransport stdioMcpTransport() {
        // 使用stdio协议创建传输对象，由于在window环境测试，这里需要指定windows下npm命令的路径
        StdioMcpTransport stdioMcpTransport = new StdioMcpTransport.Builder()
                .command(List.of(
                        "java",
                        "-Dspring.ai.mcp.server.stdio=true",
                        "-Dspring.main.web-application-type=none",
                        "-Dlogging.pattern.console=",
                        "-jar",
                        jarPath))
                .logEvents(true) // 仅当你想在日志中查看流量时
                .build();
        return stdioMcpTransport;
    }

    //sse对接mcp
//    @Bean
//    public StreamableHttpMcpTransport streamableHttpMcpTransport() {
//        StreamableHttpMcpTransport streamableHttpMcpTransport = new StreamableHttpMcpTransport.Builder()
//                .url("http://127.0.0.1:3001/sse") // SSE 事件channel地址
//                .logRequests(true) // 开启请求日志
//                .logResponses(true) // 开启响应日志
//                .build();
//        return streamableHttpMcpTransport;
//    }

    @Bean
    public McpClient mcpClient(McpTransport transport) {
        // 创建mcp客户端对象
        McpClient mcpClient = new DefaultMcpClient.Builder()
                .transport(transport)
                .build();
        return mcpClient;
    }

    @Bean
    public ToolProvider toolProvider(McpClient mcpClient) {
        // 创建工具对象
        ToolProvider toolProvider = McpToolProvider.builder()
                .mcpClients(List.of(mcpClient))
                .build();
        return toolProvider;
    }

    //返回机器人
    @Bean
    public Bot bot(QwenChatModel qwenChatModel, ToolProvider toolProvider) {
        return AiServices.builder(Bot.class)
                .chatModel(qwenChatModel)
                .toolProvider(toolProvider).build();
    }
}